/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.carbon.gate.filter;


import com.carbon.common.utils.HttpContextUtils;
import com.carbon.domain.common.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMethod;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 设置允许跨域
 *
 */
@Slf4j
public class CrossDomainFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        // 允许的源（必须指定具体域名，不能用*）
            httpServletResponse.setHeader("Access-Control-Allow-Origin", "http://localhost:9528");


        // 允许的方法（明确列出常用方法，避免用*）
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");

        // 允许的请求头（必须与前端实际发送的头匹配）
        // 包含Content-Type和token，与你的请求头access-control-request-headers一致
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "Content-Type, token");

        // 暴露的响应头（按需设置）
        httpServletResponse.setHeader("Access-Control-Expose-Headers", "Content-Type, token");

        // 允许携带凭证（已正确配置）
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");


        // 处理OPTIONS预检请求
        String method = request.getMethod();
        if (RequestMethod.OPTIONS.name().equals(method)) {
            HttpContextUtils.printJSON(httpServletResponse, ApiResult.ok());
            return;
        }

        filterChain.doFilter(servletRequest, httpServletResponse);
    }

    @Override
    public void destroy() {

    }
}
